<script setup>
import { ref, watch } from "vue";
import {
  queryPageApi,
  addEmpApi,
  delEmpApi,
  queryInfoApi,
  updateEmpApi,
} from "@/api/emp.js";
import { Plus } from "@element-plus/icons-vue";
import { queryAllApi as queryAllDeptApi } from "@/api/dept.js";

const currentPage = ref(1);
const pageSize = ref(10);
const empList = ref([]);
const total = ref("");
const empFormRef = ref();
const token = ref("");
const dialogFormVisible = ref(false);
const selectIds = ref([]);
const depts = ref([]);
const jobs = ref([
  { name: "班主任", value: 1 },
  { name: "讲师", value: 2 },
  { name: "学工主管", value: 3 },
  { name: "教研主管", value: 4 },
  { name: "咨询师", value: 5 },
  { name: "其他", value: 6 },
]);
const queryAllDept = async () => {
  const { data } = await queryAllDeptApi();
  depts.value = data;
};
const getToken = () => {
  const loginUser = JSON.parse(localStorage.getItem("loginUser"));
  if (loginUser && loginUser.token) {
    token.value = loginUser.token;
  }
};
getToken();
queryAllDept();
const genders = ref([
  { name: "男", value: 1 },
  { name: "女", value: 2 },
]);
const searchEmp = ref({ name: "", gender: "", date: [], begin: "", end: "" });
const employee = ref({
  username: "",
  name: "",
  gender: "",
  phone: "",
  job: "",
  salary: "",
  deptId: "",
  entryDate: "",
  image: "",
  exprList: [],
});
const dialogTitle = ref("");

const handleCurrentChange = (current) => {
  search();
};
const handleSizeChange = (size) => {
  search();
};
const beforeAvatarUpload = ({ type, size }) => {
  if (!type.includes("jpeg") && !type.includes("png")) {
    ElMessage.error("仅支持jpeg和png格式的图片");
    return false;
  }
  if (size / 1024 / 1024 > 10) {
    ElMessage.error("图片大小不允许超过10M");
    return false;
  }
  return true;
};
const handleSelect = (selection) => {
  selectIds.value = selection.map((item) => item.id);
};
const handleAvatarSuccess = ({ data }) => {
  employee.value.image = data;
};
const delById = (id) => {
  ElMessageBox.confirm("确认删除该员工？")
    .then(async () => {
      const { code } = await delEmpApi(id);
      if (code) {
        ElMessage.success("删除成功");
        search();
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};
const search = async () => {
  const {
    data: { rows, total: num },
  } = await queryPageApi(
    searchEmp.value.name,
    searchEmp.value.gender,
    searchEmp.value.begin,
    searchEmp.value.end,
    currentPage.value,
    pageSize.value
  );
  empList.value = rows;
  total.value = num;
};
const clear = () => {
  searchEmp.value = { name: "", gender: "", date: [], begin: "", end: "" };
  search();
};
search();
const cancel = () => {
  dialogFormVisible.value = false;
  employee.value = {
    username: "",
    name: "",
    gender: "",
    phone: "",
    job: "",
    salary: "",
    deptId: "",
    entryDate: "",
    image: "",
    exprList: [],
  };
};
const delExprItem = (index) => {
  employee.value.exprList.splice(index, 1);
};
const onClose = () => {
  employee.value = {
    username: "",
    name: "",
    gender: "",
    phone: "",
    job: "",
    salary: "",
    deptId: "",
    entryDate: "",
    image: "",
    exprList: [],
  };
};

const addEmp = () => {
  dialogFormVisible.value = true;
  dialogTitle.value = "新增员工";
  employee.value = {
    username: "",
    name: "",
    gender: "",
    phone: "",
    job: "",
    salary: "",
    deptId: "",
    entryDate: "",
    image: "",
    exprList: [],
  };
  empFormRef.value?.resetFields();
};
const addExprItem = () => {
  employee.value.exprList.push({
    company: "",
    job: "",
    begin: "",
    end: "",
    exprDate: [],
  });
};
const handleEdit = async (id) => {
  const { code, data } = await queryInfoApi(id);
  dialogFormVisible.value = true;
  dialogTitle.value = "修改员工信息";
  employee.value = data;
  employee.value.exprList.forEach((item) => {
    item.exprDate = [item.begin, item.end];
  });
};
const batchDel = () => {
  ElMessageBox.confirm("确认删除所选员工？")
    .then(async () => {
      if (selectIds.value.length === 0) {
        ElMessage.error("请先选择需要删除的员工");
        return;
      } else {
        const { code, msg } = await delEmpApi(selectIds.value);
        if (code) {
          ElMessage.success("删除成功");
          search();
          selectIds.value = [];
        } else {
          ElMessage.error(msg);
        }
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};
const save = () => {
  empFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error("表单校验不通过！");
    } else {
      let res, code, message;
      if (!employee.value.id) {
        res = await addEmpApi(employee.value);
        code = res.code;
        message = res.message;
      } else {
        res = await updateEmpApi(employee.value);
        code = res.code;
        message = res.message;
      }

      if (code) {
        ElMessage.success(
          employee.value.id ? "修改员工成功！" : "新增员工成功！"
        );
        dialogFormVisible.value = false;
        search();
      } else {
        ElMessage.error(meg);
      }
    }
  });
};

watch(
  () => searchEmp.value.date,
  (newVal, oldVal) => {
    if (newVal.length === 2) {
      searchEmp.value.begin = newVal[0];
      searchEmp.value.end = newVal[1];
    } else {
      searchEmp.value.begin = "";
      searchEmp.value.end = "";
    }
  }
);
watch(
  () => employee.value.exprList,
  (newVal, oldVal) => {
    if (employee.value.exprList && employee.value.exprList.length > 0) {
      employee.value.exprList.forEach((item) => {
        item.begin = item.exprDate[0];
        item.end = item.exprDate[1];
      });
    }
  },
  { deep: true }
);
const rules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 20, message: "用户名长度在2-20位之间", trigger: "blur" },
  ],
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 10, message: "姓名长度在2-10个字符之间", trigger: "blur" },
  ],
  gender: [{ required: true, message: "请选择性别", trigger: "change" }],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入有效的手机号",
      trigger: "blur",
    },
  ],
};
</script>

<template>
  <h1>员工管理</h1>
  <div class="container">
    <el-form :inline="true" :model="searchEmp" class="demo-form-inline">
      <el-form-item label="姓名">
        <el-input v-model="searchEmp.name" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="searchEmp.gender" placeholder="请选择">
          <el-option label="男" value="1" />
          <el-option label="女" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="入职时间">
        <el-date-picker
          v-model="searchEmp.date"
          type="daterange"
          range-separator="到"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button type="info" @click="clear">清空</el-button>
      </el-form-item>
    </el-form>
  </div>

  <div class="container">
    <el-button type="primary" @click="addEmp">新增员工</el-button>
    <el-button type="danger" @click="batchDel">批量删除</el-button>
  </div>

  <div class="container">
    <el-table
      :data="empList"
      stripe
      style="width: 100%"
      @selection-change="handleSelect"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="姓名" width="180" />
      <el-table-column label="性别" width="180" align="center">
        <template #default="{ row }">
          {{ row.gender === 1 ? "男" : "女" }}
        </template>
      </el-table-column>
      <el-table-column prop="image" label="头像">
        <template #default="{ row }">
          <img :src="row.image" alt="" height="40px" />
        </template>
      </el-table-column>
      <el-table-column prop="deptName" label="所属部门" width="180" />
      <el-table-column prop="job" label="职位" width="180">
        <template #default="{ row: { job } }">
          <span v-if="job == 1">班主任</span>
          <span v-else-if="job == 2">讲师</span>
          <span v-else-if="job == 3">学工主管</span>
          <span v-else-if="job == 4">咨询师</span>
          <span v-else-if="job == 5">其他</span>
          <span v-else>其他</span>
        </template>
      </el-table-column>
      <el-table-column prop="entryDate" label="入职日期" width="180" />
      <el-table-column prop="updateTime" label="最后操作时间" width="180" />
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button type="primary" @click="handleEdit(row.id)">编辑</el-button>
          <el-button type="danger" @click="delById(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <div class="container pagination">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 30, 40]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <el-dialog
    v-model="dialogFormVisible"
    :title="dialogTitle"
    width="800"
    @close="onClose"
  >
    <el-form
      label-width="80px"
      :model="employee"
      :rules="rules"
      ref="empFormRef"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="employee.username"
              placeholder="2-20个字"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="employee.name"
              placeholder="请输入员工姓名"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="employee.gender" placeholder="请选择性别">
              <el-option
                v-for="item in genders"
                :label="item.name"
                :value="item.value"
                :key="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="employee.phone"
              placeholder="请输入员工手机号"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="职位">
            <el-select v-model="employee.job" placeholder="请选择职位">
              <el-option
                v-for="item in jobs"
                :label="item.name"
                :value="item.value"
                :key="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="薪资">
            <el-input
              v-model="employee.salary"
              placeholder="请输入员工薪资"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="所属部门">
            <el-select v-model="employee.deptId" placeholder="请选择部门">
              <el-option
                v-for="item in depts"
                :label="item.name"
                :value="item.id"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入职日期">
            <el-date-picker
              v-model="employee.entryDate"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="头像">
            <el-upload
              class="avatar-uploader"
              action="/api/upload"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :show-file-list="false"
              :headers="{ token }"
            >
              <img v-if="employee.image" :src="employee.image" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="工作经历">
            <el-button type="success" @click="addExprItem"
              >添加工作经历</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-for="(expr, index) in employee.exprList">
        <el-col :span="10">
          <el-form-item label="时间">
            <el-date-picker
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              v-model="expr.exprDate"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="公司" label-width="55px">
            <el-input
              placeholder="请输入公司名称"
              v-model="expr.company"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="职位" label-width="60px">
            <el-input placeholder="请输入职位" v-model="expr.job"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-form-item label-width="10">
            <el-button type="danger" @click="delExprItem(index)"
              >删除</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="save">保存</el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.container {
  margin: 10px 0;
  .el-form-item:nth-child(1) {
    width: 180px;
  }
  .el-form-item:nth-child(2) {
    width: 140px;
  }
  .el-form-item:nth-child(3) {
    width: 350px;
  }
}
:deep(.el-date-editor.el-input) {
  width: 100% !important;
}
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 30px;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.el-upload {
  width: 120px;
  height: 120px;
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-upload img {
  width: 100% !important;
  height: 100% !important;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  text-align: center;
}
</style>
